//
//  Recharge.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/21.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import SwiftyStoreKit
import RxSwift

class Recharge {
    
    var disposeBag = DisposeBag()
    
    static let shareInstance = Recharge()
    static var `default`: Recharge { return shareInstance  }
    var isSandbox: Bool
    
    init(sandbox: Bool = false) {
        self.isSandbox = Config.default.isSandbox
    }
    
    func recharge(_ productId: String, complete: (()->Void)?) {
        
        startAnimating()
        ///检索并支付商品
        SwiftyStoreKit.purchaseProduct(productId, quantity: 1, atomically: true) { [weak self] (result) in
            
            switch result {
            case .success(let purchase):
                ///验证支付
                self?.verifyReceipt(productId: purchase.productId, compelete: {
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                    complete?()
                })
                break
                
            case .error(let error):
                stopAnimating()
                
                var msg: String?
                switch error.code {
                case .unknown: //print("Unknown error. Please contact support")
                    msg = "未知错误"
                case .clientInvalid: //print("Not allowed to make the payment")
                    msg = "不允许交易"
                case .paymentCancelled: //
                    break
//                    msg = "取消交易"
                case .paymentInvalid: //print("The purchase identifier was invalid")
                    msg = "购买标识符无效"
                case .paymentNotAllowed: //print("The device is not allowed to make the payment")
                    msg = "该设备不允许付款"
                case .storeProductNotAvailable: //print("The product is not available in the current storefront")
                    msg = "该产品在目前的店面中不可用"
                case .cloudServicePermissionDenied: //print("Access to cloud service information is not allowed")
                    msg = "不允许访问云服务信息"
                case .cloudServiceNetworkConnectionFailed: //print("Could not connect to the network")
                    msg = "无法连接到网络"
                case .cloudServiceRevoked: //print("User has revoked permission to use this cloud service")
                    msg = "用户已撤销使用此云服务的权限。"
                }
                if msg != nil {
                    lsf_alert("交易失败", message: msg!)
                }
                
            }
        }
        
    }
    
    
    ///向服务器验证凭据
    func verifyReceipt(productId: String, compelete:VoidBlock?) {
        guard let receiptData = receiptData() else {
            stopAnimating()
            return
        }
        let receipt = receiptData.base64EncodedString(options: [])
        let chooseEnv = 1//self.isSandbox ? 0 : 1
        let quantity = 1
        

        shuren60Provider.rx
            .request(.coinCertificate(receipt: receipt, chooseEnv: chooseEnv, productId: productId, quantity: quantity))
            .asObservable()
            .mapRespnseJson()
            .subscribe(onNext: { (data) in
                guard let coin = data as? Int else { return }
                AccountStorage.default.account.goldCoin = coin
                AccountStorage.default.updateAccount()
        }, onError: { (error) in
            //交易失败
            stopAnimating()
            showError(error)
        }, onCompleted: {
            //交易成功
            stopAnimating()
            compelete?()
        }).disposed(by: disposeBag)
    }
    
    
    func receiptData() -> Data? {
        guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else { return nil }
        let data = try? Data.init(contentsOf: appStoreReceiptURL)
        return data
    }
    
    ///自动检查支付完成未验证的交易
    func completeIapTransactions() {
        SwiftyStoreKit.completeTransactions {  [weak self] (purchases) in
            for purchase in purchases {
                if purchase.transaction.transactionState == .purchased ||
                    purchase.transaction.transactionState == .restored {
                    
                    self?.verifyReceipt(productId: purchase.productId, compelete: {
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    })
                }
            }
        }
    }
}
